package org.apache.ocean;

import org.apache.lucene.index.IndexReader;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author jasonr
 */
public class MultiIndexSearcher extends CIndexSearcher {
  public MultiIndexSearcher(IndexReader indexReader) {
    super(indexReader);
  }

  public List<SegmentIndexSearcher> getSegmentIndexSearchers() {
    try {
      IndexReader indexReader = getIndexReader();
      if (StringUtils.equals("org.apache.lucene.index.SegmentReader", indexReader.getClass().getName())) {
        List<SegmentIndexSearcher> indexSearchers = new ArrayList<SegmentIndexSearcher>(1);
        indexSearchers.add(new SegmentIndexSearcher(indexReader));
        return indexSearchers;
      } else if (StringUtils.equals("org.apache.lucene.index.MultiSegmentReader", indexReader.getClass().getName())) {
        IndexReader[] subReaders = (IndexReader[])FieldUtil.getFieldValue("subReaders", indexReader);
        List<? extends IndexReader> indexReaders = Arrays.asList(subReaders);
        List<SegmentIndexSearcher> indexSearchers = new ArrayList<SegmentIndexSearcher>(indexReaders.size());
        for (IndexReader subIndexReader : indexReaders) {
          SegmentIndexSearcher indexSearcher = new SegmentIndexSearcher(subIndexReader);
          indexSearchers.add(indexSearcher);
        }
        return indexSearchers;
      } else {
        throw new RuntimeException("unknown reader class type: " + indexReader.getClass().getName());
      }
    } catch (Exception exception) {
      throw new RuntimeException(exception);
    }
  }
}
